package com.fishingwithme.domain.user;

import com.fishingwithme.domain.credit.CreditService;
import com.fishingwithme.infrastructure.cache.CacheService;
import com.fishingwithme.infrastructure.mapper.SpotUserMapper;
import com.fishingwithme.infrastructure.utils.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

/**
 * 用户名密码登录服务实现
 * 实现用户名密码相关的用户操作
 */
@Service
public class UsernamePasswordServiceImpl implements UsernamePasswordService {

    @Autowired
    private SpotUserMapper spotUserMapper;

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private UserService userService;

    @Autowired
    private CreditService creditService;

    @Autowired
    private CacheService cacheService;

    @Override
    public SpotUser loadUserByUsername(String username) {
        SpotUser spotUser = cacheService.getUserByUsername(username);
        if(spotUser != null) {
            return spotUser;
        }
        spotUser = spotUserMapper.findByUsername(username); 
        if(spotUser != null) {
            cacheService.cacheUserByUsername(spotUser);
        }

        return spotUser;
    }

    @Override
    @Transactional
    public SpotUser registerUser(String username, String password, String email, String nickname) {
        // 检查用户名是否已存在
        if (existsByUsername(username)) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 创建新用户
        SpotUser user = new SpotUser();
        String uuid = UUID.randomUUID().toString();
        user.setUserId(idGenerator.nextId());
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setUnionId(uuid);
        user.setOpenId(uuid);
        user.setEmail(email);
        user.setNickname(StringUtils.hasText(nickname) ? nickname : username);
        user.setAdmin(false);
        
        // 设置默认头像
        user.setAvatarUrl("https://via.placeholder.com/150");
        
        Date now = new Date();
        user.setRegisterTime(now);
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        user.setCreatedBy(user.getUserId());
        user.setUpdatedBy(user.getUserId());

        // 保存用户
        spotUserMapper.insertUser(user);
        
        // 初始化用户积分记录
        creditService.addUserRecord(user.getUserId());
        
        return user;
    }

    @Override
    @Transactional
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        SpotUser user = userService.loadUserByUserId(userId);
        if (user == null) {
            return false;
        }

        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false;
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        user.setUpdatedAt(new Date());
        user.setUpdatedBy(userId);
        
        spotUserMapper.updateById(user);
        return true;
    }

    @Override
    @Transactional
    public boolean resetPassword(String username, String newPassword) {
        SpotUser user = loadUserByUsername(username);
        if (user == null) {
            return false;
        }

        user.setPassword(passwordEncoder.encode(newPassword));
        user.setUpdatedAt(new Date());
        user.setUpdatedBy(user.getUserId());
        
        spotUserMapper.updateById(user);
        return true;
    }

    @Override
    public boolean existsByUsername(String username) {
        return spotUserMapper.findByUsername(username) != null;
    }
}